package com.zhouyu.mybatisSpring;

import com.zhouyu.mapper.OrderMapper;
import com.zhouyu.mapper.UserMapper;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;

import java.io.IOException;
import java.util.Map;

public class ZhouyuImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {


	/**
	 * （3）通过后import，注册需要的BeanDefinition
	 *
	 * @param importingClassMetadata annotation metadata of the importing class
	 * @param registry               current bean definition registry
	 */
	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
//
//		AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
//		beanDefinition.setBeanClass(ZhouyuFactoryBean.class);
//		beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(UserMapper.class);
//		registry.registerBeanDefinition("userMapper", beanDefinition);
//
//		AbstractBeanDefinition beanDefinition2 = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
//		beanDefinition2.setBeanClass(ZhouyuFactoryBean.class);
//		beanDefinition2.getConstructorArgumentValues().addGenericArgumentValue(OrderMapper.class);
//		registry.registerBeanDefinition("orderMapper", beanDefinition2);



		//扫描路径
		Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(ZhouyuMapperScan.class.getName());
		String path = (String) annotationAttributes.get("value");
		System.out.println("扫描路径：" + path);


		ZhouyuBeanDefinitionScanner scanner = new ZhouyuBeanDefinitionScanner(registry);
		scanner.addIncludeFilter(new TypeFilter() {
			@Override
			public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
				return true;
			}
		});

		scanner.scan(path);

	}
}
